package com.cskaoyan.transaction;

import com.cskaoyan.transaction.util.JdbcUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;

/**
 * @ClassName BatchTransaction_2
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/2/7 16:41
 * @Version V1.0
 **/
public class BatchTransaction_2 {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Savepoint savepoint = null;
        try {
            connection = JdbcUtil.getConnection();
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement("update account set money = money - ? where id = ?");
            //进行批量转账 boss----转出     1、2、3、4转入
            for (int i = 1; i < 5; i++) {
                //员工转入指定的金额
                preparedStatement.setDouble(1, -100.0);
                preparedStatement.setInt(2, i);
                preparedStatement.executeUpdate();
                if(i == 4){
                    int a = 1 / 0;
                }
                //老板转出指定的金额
                preparedStatement.setDouble(1, 100);
                preparedStatement.setInt(2, 5);
                preparedStatement.executeUpdate();
                //每当转账完成一名员工之后，设置一个存档点；后续如果转账失败，则不用全部回退
                savepoint = connection.setSavepoint();
            }
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if(savepoint != null){
                    //如果转账过程出错，那么回滚到最近的回滚点/存档点
                    connection.rollback(savepoint);
                    //如果回退到存档点，那么需要再次执行commit提交
                    connection.commit();
                }else {
                    //如果没有任何的存档点，则直接回退到最开始的位置
                    connection.rollback();
                }
            }catch (Exception e1){
            }

        }
    }
}
